<template>
  <div class="app-container">
    <el-form ref="banner" :rules="rules" :model="banner" label-width="150px">
      <el-form-item label="banner名称" prop="bannerName">
        <el-input v-model="banner.bannerName" placeholder="请输入" />
      </el-form-item>

      <el-form-item label="视频文件">
        <div class="upload-demo">
          <div
            class="el-upload el-upload--text txt-l"
            @click="handleClick"
            @keydown="handleKeydown"
          >
            <el-button
              slot="trigger"
              size="small"
              type="primary"
              class="el-button el-button--primary el-button--small"
            >选取文件</el-button>
            <input
              ref="input"
              type="file"
              name="file"
              class="el-upload__input"
              @change="handleChange"
            >
            <div slot="tip" class="el-upload__tip">上传视频请提前压缩</div>
          </div>
        </div>
        <div v-if="banner.bannerImage" style="width: 145px;height: 145px;">
          <video-player
            ref="videoPlayer"
            :playsinline="true"
            :options="video_Config"
            class="video-player vjs-custom-skin"
          />
        </div>
      </el-form-item>

      <div class="op-container">
        <el-button type="primary" @click="handlePublish('banner')">提交</el-button>
        <el-button @click="handleCancel('banner')">取消</el-button>
      </div>
    </el-form>
    <el-dialog
      :visible.sync="dialogVisible"
      :show-close="false"
      :close-on-click-modal="false"
      title="视频模块"
      width="30%"
    >
      <div class="progressContent">
        <el-progress v-if="!change_video_status" :percentage="videoPercentage" />
        <div v-if="!change_video_status" class="mt10">文件上传中</div>
        <div v-else class="mt10">服务器转码中...</div>
        <div class="mt10">请耐心等待</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}

.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader .el-upload {
  width: 145px;
  height: 145px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
.op-container {
  padding-left: 100px;
}
</style>

<script>
import { bannerSave } from '@/api/banner'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import upload from '@/components/Upload'
import {
  getVideoToken,
  setVideoPfop,
  getVideoPfopStatus
} from '@/api/video'
import uploadFun from '@/utils/qiniu'
import videoConfig from '@/utils/videoConfig'
export default {
  name: 'GoodsEdit',
  components: { 'pa-upload': upload },

  data() {
    var validImg = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请上传图片'))
      } else {
        callback()
      }
    }
    return {
      action: `${process.env.BASE_API}/vms/v1/image/upload`,
      banner: {
        bannerName: '',
        bannerImage: ''
      },
      rules: {
        bannerName: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        bannerImage: [
          { required: true, validator: validImg, trigger: 'blur' }
        ]
      },
      videoPercentage: 0,
      uploading_video: false, // 新增部分
      change_video_status: false,
      video_Config: videoConfig,
      show_video: true,
      timer: null,
      dialogVisible: false
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  mounted() {
    const self = this
    clearInterval(self.timer)
    if (!self.$store.state.video.videoToken) {
      getVideoToken().then(res => {
        self.$store.commit('SET_VIDEOTOKEN', res.data.data.token)
      })
    }
  },

  methods: {
    handleCancel: function(formName) {
      this.$refs[formName].resetFields()
    },
    handlePublish: function(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const params = this.banner
          bannerSave(params).then(res => {
            this.$notify.success({
              title: '成功',
              message: '添加成功'
            })
            this.$router.push({ name: 'bannerList' })
          }).catch(response => {
            MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
              confirmButtonText: '确定',
              type: 'error'
            })
          })
        }
      })
    },
    handleClick() {
      this.$refs.input.value = ''
      this.$refs.input.click()
    },
    handleChange(ev) {
      const files = ev.target.files
      if (!files) return
      this.uploadFiles(files)
    },
    uploadFiles(files) {
      const self = this
      const observer = {
        next(res) {
          self.videoPercentage = parseInt(res.total.percent)
        },
        complete(res) {
          if (res.key) {
            setVideoPfop({
              key: res.key
            }).then(res => {
              self.change_video_status = true
              self.timer = setInterval(() => {
                getVideoPfopStatus({
                  id: res.data.data.persistentId
                }).then(res => {
                  res = res.data.data
                  if (res[0].status.code === 0) {
                    clearInterval(self.timer)
                    self.dialogVisible = false
                    self.change_video_status = false
                    self.video_Config[`sources`][0].src = res[0].url
                    self.banner.bannerImage = res[0].url
                  }
                })
              }, 1000)
            })
          }
        }
      }
      self.dialogVisible = true
      self.subscription = uploadFun(
        self.$store.state.video.videoToken,
        files[0],
        observer
      )
    },
    close() {
      const self = this
      self.change_video_show = false
      self.dialogVisible = false
      self.change_video_status = false
      if (self.subscription) {
        self.subscription.unsubscribe()
      }
      clearInterval(self.timer)
    },
    beforeDestroy() {
      clearInterval(self.timer)
    },
    handleKeydown(e) {
      if (e.target !== e.currentTarget) return
      if (e.keyCode === 13 || e.keyCode === 32) {
        this.handleClick()
      }
    }
  }
}
</script>
